package com.langyiquan.front.controller;

import com.langyiquan.bo.UserInfoBO;
import com.langyiquan.exception.http.ParamException;
import com.langyiquan.pojo.Users;
import com.langyiquan.service.UserService;
import com.langyiquan.utils.DateUtil;
import com.langyiquan.utils.UnifyResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Api(value = "用户中心", tags = {"用户中心相关接口"})
@RestController
@RequestMapping("user")
public class UserController extends BaseController{

    @Autowired
    private UserService userService;

    @Autowired
    private Environment env;

    @ApiOperation(value = "获取用户信息",notes = "获取用户信息",httpMethod = "GET")
    @GetMapping("info")
    public UnifyResponse info(HttpServletRequest request){
        String userId = getPassportUserId(request);
        Users user = userService.queryUserInfo(userId);
        user.setPassword(null);
        return UnifyResponse.success(user);
    }


    @ApiOperation(value = "修改用户信息",notes = "修改用户信息",httpMethod = "POST")
    @PostMapping("update")
    public UnifyResponse update(@RequestBody @Valid UserInfoBO userInfoBO, BindingResult bindingResult, HttpServletRequest request){

        String userId = getPassportUserId(request);

        if(bindingResult.hasErrors()){
            Map<String,String> errorsMap = getBindingResultErrors(bindingResult);
            String errCode = errorsMap.entrySet().iterator().next().getValue();
            throw new ParamException(Integer.parseInt(errCode));
        }

        Users user = userService.updateUserInfo(userId,userInfoBO);

        return UnifyResponse.success(user);
    }


    @ApiOperation(value = "上传用户头像",notes = "上传用户头像",httpMethod = "POST")
    @PostMapping("uploadFace")
    public UnifyResponse uploadFace(MultipartFile file, HttpServletRequest request){

        String userId = getPassportUserId(request);

        String fileSpace = env.getProperty("resource.upload-location");

        String uploadPathPrefix = File.separator + "faces" + File.separator;

        if(file != null){

            FileOutputStream fileOutputStream = null;

            String fileName = file.getOriginalFilename();

            String fileNameArr[] = fileName.split("\\.");

            String suffix = fileNameArr[fileNameArr.length - 1];

            if(!suffix.equalsIgnoreCase("png") && !suffix.equalsIgnoreCase("jpg") && !suffix.equalsIgnoreCase("jpeg") && !suffix.equalsIgnoreCase("gif")){
                throw new ParamException(1006);
            }

            String newFileName = "face-" + userId + "." + suffix;

            // 上传的头像最终保存的位置
            String finalFacePath = fileSpace + uploadPathPrefix + File.separator + newFileName;
            uploadPathPrefix += ("/"+newFileName);

            File outFile = new File(finalFacePath);
            if (outFile.getParentFile() != null) {
                // 创建文件夹
                outFile.getParentFile().mkdirs();
            }

            // 文件输出保存到目录
            try {
                fileOutputStream = new FileOutputStream(outFile);
                InputStream inputStream = file.getInputStream();
                IOUtils.copy(inputStream, fileOutputStream);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fileOutputStream != null) {
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            String imageServerUrl = env.getProperty("resource.server-url");

            String avatarUrl = imageServerUrl+uploadPathPrefix;
            userService.updateUserFace(userId,avatarUrl);
            Map<String,String> avatarMap = new HashMap<>();
            avatarMap.put("avatarUrl",avatarUrl+"?time="+ DateUtil.getCurrentDateString(DateUtil.DATE_PATTERN));
            return UnifyResponse.success(avatarMap);
        }else{
            throw new ParamException(1007);
        }

    }


}
